package com.zhq.blog.manage.domain.controller.money;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

import net.sf.json.JSONObject;

import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zhq.blog.core.domain.money.CardRecord;
import com.zhq.blog.core.domain.search.CardRecordSearch;
import com.zhq.blog.manage.domain.controller.BaseController;
import com.zhq.blog.manage.domain.controller.BossModel;

@Controller
@Scope("prototype")
@RequestMapping("/admin/money/cardRecord/*")
public class CardRecordController extends BaseController {
	
	@RequestMapping()
    public BossModel index(String viewState,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable) throws UnsupportedEncodingException{
		CardRecordSearch search = null;
		if (viewState != null && !viewState.trim().equals("")) {
			// 解析传递过来的查询json字符串
			search = (CardRecordSearch) JSONObject.toBean(JSONObject.fromObject(new String(Base64.getDecoder().decode(viewState), "UTF-8")), CardRecordSearch.class);
			return createModel("admin/money/cardRecord/list")
					.add("cardRecordSearch", search)
					.add("viewState", viewState)
					.add("cardRecordPage",context.getCardRecordRepository().findAll(new CardRecord().selectCondition(search),pageable));
		} else {
			search = new CardRecordSearch();
			return createModel("admin/money/cardRecord/list").add("cardRecordSearch", search).add("viewState","").add("cardRecordPage", context.getCardRecordRepository().findAll(pageable));

		}
	}
	
	@RequestMapping(value = "index", method = RequestMethod.POST)
	public BossModel index(CardRecordSearch search,@PageableDefault(page = 0, size = DEFAULT_PAGE_SIZE, sort = "createdDate", direction = Sort.Direction.DESC) Pageable pageable)throws UnsupportedEncodingException {
		return createModel("admin/money/cardRecord/list")
				.add("cardRecordPage", context.getCardRecordRepository().findAll(new CardRecord().selectCondition(search),pageable))
				.add("viewState",Base64.getEncoder().encodeToString(JSONObject.fromObject(search).toString().getBytes("UTF-8")));
	}
	
	@RequestMapping(value="delete",method= RequestMethod.POST)
	public BossModel delete(String viewState,long id,@PageableDefault(page = 0,size = DEFAULT_PAGE_SIZE,sort = "id",direction = Sort.Direction.DESC) Pageable pageable){
		context.getCardRecordRepository().delete(id);
		return createModel("admin/money/cardRecord/cardRecord_table").add("cardRecordSearch",context.getCardRecordRepository().findAll(pageable)).add("viewState", viewState);
	}

}
